package org.shoukaiseki.test.corssorigin.demo1;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class CorssFilter1 implements Filter {

    @Value("${hkedou.corss.allowedorigins}")
    String[] allowedorigins;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        for (String origin:allowedorigins ) {
//            response.setHeader("Access-Control-Allow-Origin", origin);
//            response.setHeader("allowedOrigins", origin);
        }
        //当 ajax 设置了  xhrFields: { withCredentials: true }, 携带cookie跨域访问时,不能设置跨域 *
        //测试机子可以用这种方式,但是正式服务推荐使用 实际地址,例如:[http://localhost:8080]
//         response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
//        response.setHeader("allowedOrigins",request.getHeader("Origin"));
//        response.setHeader("Access-Control-Allow-Origin","*");
        //允许跨域证书
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
